let util = {};
// 判断是否授权和登录
util.doJudgeAuthOrLogin = async function(vm) {
	let {
		redirect_uri,
		authorizationStoragePre,
		userinfoStoragePre,
		merberIdStorage
	} = vm.$json('wxPublic');
	let {
		shopIdApp,
		authorizationStorageAppPre,
		userinfoStorageAppPre
	} = vm.$json('appPublic');
	let url, shopId, shopAppId, userId, _memberId, hasLogin,sign;

	// #ifdef H5
	var reg = new RegExp("(^|&)state=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg)[2];
	url = r.split('_')[0] + window.location.host;
	 
	shopId = uni.getStorageSync(`SHOPID_` + url) || '';
	shopAppId = uni.getStorageSync(`SHOPAPPID_` + url) || '';
	userId = uni.getStorageSync(`${authorizationStoragePre}` + url) || '';
	_memberId = uni.getStorageSync(`${merberIdStorage}` + shopId) || '';
	sign = "H5";
	// #endif
	//#ifdef APP-PLUS
	shopId = shopIdApp;
	url = shopIdApp;
	sign = "APP";
	userId = uni.getStorageSync(`${authorizationStorageAppPre}` + url) || '';
	//#endif

	hasLogin = vm.hasLogin;

	if (userId === '') { // 没有授权 去授权
		// console.log('没有授权 去授权, userid=', userId);
		// #ifdef H5
		// 微信公众号
		if (vm.$wechat && vm.$wechat.isWechat()) {
			const encodeIndexUrl = encodeURIComponent(redirect_uri);
			location.href =
				`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${shopAppId}&redirect_uri=${encodeIndexUrl}&response_type=code&scope=snsapi_userinfo&state=${shopId}_${_memberId}_${shopAppId}#wechat_redirect`;
		}
		// #endif
		//#ifdef APP-PLUS
		uni.navigateTo({
			url: '/pages/system/login',
		});
		// #endif
	} else if (!hasLogin) { // 已授权 没有登录 去登录
		// console.log('已授权 没有登录 去登录, hasLogin=', hasLogin);
		// // #ifdef APP-PLUS
		// uni.navigateTo({
		// 	url: '/pages/system/login',
		// });
		// // #endif
		uni.showLoading({
			title: '登录中...',
		});
		await vm.$https.get('/shopApp/wechat/autoLogin', {
			userId: userId,
			shopId: shopId,
			sign: sign
		}, null, false).then((res) => {
			// console.log(res);
			let {
				userId,
				headimgurl,
				nickname,
				sessionId,
				isBindPhone
			} = res.data.data;
			uni.setStorageSync(`sessionId_` + url, sessionId);
			// #ifdef H5

			uni.setStorageSync(`${authorizationStoragePre}` + url, userId);
			uni.setStorageSync(`${userinfoStoragePre}` + url, {
				headimgurl: headimgurl,
				nickname: nickname,
				isBindPhone: isBindPhone,
				userId: userId
			});
			//更新登陆状态
			// uni.getStorageSync({
			// 	key: `${userinfoStoragePre}` + url,
			// 	success: (res) => {
			// 		vm.login(res.data);
			// 	}
			// });
			let dd = uni.getStorageSync(`${userinfoStoragePre}` + url);
			if (dd) {
				vm.login(dd);
			}
			// #endif
			//#ifdef APP-PLUS

			uni.setStorageSync(`${authorizationStorageAppPre}` + url, userId);
			uni.setStorageSync(`${userinfoStorageAppPre}` + url, {
				headimgurl: headimgurl,
				nickname: nickname,
				isBindPhone: isBindPhone,
				userId: userId
			});
			//更新登陆状态
			// uni.getStorage({
			// 	key: `${userinfoStorageAppPre}` + url,
			// 	success: (res) => {
			// 		vm.login(res.data);
			// 	}
			// });
			let dd = uni.getStorageSync(`${userinfoStorageAppPre}` + url);
			if (dd) {
				vm.login(dd);
			}
			// #endif
			// uni.hideLoading();
			return true;
		}).catch(error => {
			console.log(error);
			return false;
		});
		uni.hideLoading();
	} else { // 已授权已登录返回状态true
		// console.log('已授权已登录返回状态true');
		if (!vm.$store.state.isBindPhone) {
			uni.redirectTo({
				url: `/pages/system/bindPhone?type=noBind`,
			});
		}
		return true;
	}
	return false;
}

// 没有登录时，跳转登录页面进行登录，不再询问授权
// 更新sessionId，同事更新登录状态
util.doUpdateSession = async function(vm) {
	let shopId, userId, url,sign;
	// #ifdef H5
	let {
		authorizationStoragePre,
		userinfoStoragePre
	} = vm.$json('wxPublic');
	var reg = new RegExp("(^|&)state=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg)[2];
    url = r.split('_')[0] + window.location.host;
	shopId = uni.getStorageSync(`SHOPID_` + url) || '';
	userId = uni.getStorageSync(`${authorizationStoragePre}` + url) || '';
	sign = "H5";
	//#endif
	//#ifdef APP-PLUS
	let {
		shopIdApp,
		authorizationStorageAppPre,
		userinfoStorageAppPre
	} = vm.$json('appPublic');
	userId = uni.getStorageSync(`${authorizationStorageAppPre}${shopIdApp}`) || '';
	shopId = shopIdApp;
	url = shopIdApp;
	 sign = "APP";
	//#endif
	// console.log('util js - shopId: ', shopId, 'userId: ', userId);
	await vm.$https.get('/shopApp/wechat/autoLogin', {
		userId: userId,
		shopId: shopId,
		sign: sign
	}, null, false).then((res) => {
		// console.log('方法doUpdateSession内：更新session调接口ing');
		// console.log(res);
		// if (res.data && res.data.code === 200 && res.data.success) {
		let data = res.data.data;
		let {
			userId,
			headimgurl,
			nickname,
			isBindPhone
		} = data;
		uni.setStorageSync('nickname', nickname);
		//#ifdef APP-PLUS
		uni.setStorageSync(`${authorizationStorageAppPre}` + url, userId);
		uni.setStorageSync(`${userinfoStorageAppPre}` + url, {
			headimgurl: headimgurl,
			nickname: nickname,
			isBindPhone: isBindPhone,
			userId: userId
		});
		//更新登陆状态
		uni.getStorage({
			key: `${userinfoStorageAppPre}` + url,
			success: (res) => {
				vm.login(res.data);
			}
		});
		//#endif
		// #ifdef H5
		uni.setStorageSync(`${authorizationStoragePre}` + url, userId);
		uni.setStorageSync(`${userinfoStoragePre}` + url, {
			headimgurl: headimgurl,
			nickname: nickname,
			isBindPhone: isBindPhone,
			userId: userId
		});
		//更新登陆状态
		uni.getStorage({
			key: `${userinfoStoragePre}` + url,
			success: (res) => {
				vm.login(res.data);
			}
		});
		//#endif

		uni.hideLoading();
		// }
	}).catch(error => {
		console.log(error);
	});
	// console.log('方法doUpdateSession内：更新session调接口结束');
}

export default util;
